package com.itany.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.itany.SocketServer;
import com.itany.constant.ResponseConstant;
import com.itany.exception.RequestParamsException;
import com.itany.order.service.IOrderService;

import com.itany.pojo.Order;
import com.itany.pojo.User;
import com.itany.vo.ActionResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;


@Controller
@RequestMapping("/order")
public class TestOrderController {

    @Reference
    private IOrderService orderService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @RequestMapping("/findshoppingcart")
    @ResponseBody
    public ActionResult findshoppingcart(HttpServletRequest request) {
        Cookie[] cks = request.getCookies();
        ActionResult ac = new ActionResult();
        User user = null;
        if (null != cks) {
            for (Cookie ck : cks) {
                if ("TT_TOKEN".equals(ck.getName())) {
                    String token = ck.getValue();
                    String str = redisTemplate.opsForValue().get("USER_TOKEN::" + token);
                    user = JSONObject.parseObject(str, User.class);
                }
            }
            try {
                List<Map<Object, Object>> findshoppingcart = orderService.findshoppingcart(user);
                ac.setData(findshoppingcart);
               ac.setStatus(ResponseConstant.RESPONSE_SUCCESS);
            } catch (Exception e) {
                e.printStackTrace();
                ac.setMsg("服务器内部异常");
                ac.setStatus(ResponseConstant.SERVER_ERROR);
            }
        } else {
            ac.setMsg("cookie已被禁用，请启用");
            ac.setStatus(ResponseConstant.RESPONSE_FAIL);
        }
        return ac;
    }

    /**
     * 获取总价格
     * @param selectedIndexArrayStr
     * @return
     */
    @RequestMapping("/countmoney")
    @ResponseBody
    public ActionResult countmoney(String selectedIndexArrayStr){
        ActionResult ac =new ActionResult();
        try {
            List<String> selectedIndexArray =JSON.parseArray(selectedIndexArrayStr,String.class);
            BigDecimal paymentAmount = orderService.countMoney(selectedIndexArray);
            ac.setData(paymentAmount);
            ac.setStatus(ResponseConstant.RESPONSE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            ac.setStatus(ResponseConstant.SERVER_ERROR);
            ac.setMsg("服务器内部错误");
        }
        return ac;
    }


    @RequestMapping("/generateOrder")
    //TODO:Order表的设计有很大的问题--主键错乱，默认值错乱，存储钱的错乱
    @ResponseBody
    public ActionResult generateOrder(String selectedIndexArrayStr,HttpServletRequest request){
        ActionResult ac =new ActionResult();
        User user = null;
        Cookie[] cks = request.getCookies();
        if (null != cks) {
            for (Cookie ck : cks) {
                if ("TT_TOKEN".equals(ck.getName())) {
                    String token = ck.getValue();
                    String str = redisTemplate.opsForValue().get("USER_TOKEN::" + token);
                    user = JSONObject.parseObject(str, User.class);
                }
            }
            try {
                List<String> selectedIndexArray = JSON.parseArray(selectedIndexArrayStr, String.class);
                Order order = orderService.generateOrder(selectedIndexArray, user);
                ac.setData(order);
                ac.setStatus(ResponseConstant.RESPONSE_SUCCESS);
            }catch (RequestParamsException e){
                ac.setStatus(ResponseConstant.REQUEST_PARAMETER_ERROR);
                ac.setMsg(e.getMessage());
            }catch (Exception e) {
                e.printStackTrace();
                ac.setStatus(ResponseConstant.SERVER_ERROR);
                ac.setMsg("服务器内部错误");
            }

        }else{
            ac.setMsg("cookie已被禁用，请启用");
            ac.setStatus(ResponseConstant.RESPONSE_FAIL);
        }
        return ac;
    }




    /**
     * 获取二维码
     * @param response
     * @throws Exception
     */
    @RequestMapping("/createImg")
    public void createImg(HttpServletResponse response)throws  Exception{
        response.setHeader("Pragma","No-cache");
        response.setContentType("image/jpeg");
        //获取qrCode
        String qrCode = orderService.getQrCode();
        //二维码操作
        Map<EncodeHintType,Object> map  = new HashMap<EncodeHintType,Object>();
        map.put(EncodeHintType.CHARACTER_SET,"UTF-8");
        BitMatrix bitMatrix = new MultiFormatWriter()
                .encode(qrCode, BarcodeFormat.QR_CODE,200,200,map);
        //矩阵对象转换为流对象
        MatrixToImageWriter.writeToStream(bitMatrix,"jpeg",response.getOutputStream());
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }

    /**
     * 支付成功回调方法
     * @return
     */
    @RequestMapping("/paySuccess/{no}")
    @ResponseBody
    public String paySuccess(@PathVariable("no") String no)throws Exception{
        /**
         * 先select状态看是不是已完成订单,如果是则不做操作
         *                           如果不是则更新加跳转页面
         */
        System.out.println("no====="+no);
        CopyOnWriteArraySet<SocketServer> set = SocketServer.set;
        for(SocketServer socketServer:set){
            if(socketServer.getUserId().equalsIgnoreCase("1")){
                socketServer.getSession().getBasicRemote().sendText("1");
            }
        }
        return "success";
    }
}
